package com.binguo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.binguo.api.form.CustomerForm;
import com.binguo.api.form.CustomerGroupFaceForm;
import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import com.binguo.common.exception.ServiceException;
import com.binguo.model.mapper.CashierDeskMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.socket.SocketService;
import com.binguo.socket.service.MenJinSocketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

/**
 * @author yuritian
 * @Title: MenJinSocketController
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2020-02-2109:31
 */
@Api(tags = "门禁Socket测试")
@RestController
@RequestMapping
public class MenJinSocketController {

    @Autowired
    MenJinSocketService menJinSocketService;

    @Autowired
    PayCardRepository payCardRepository;

    @Autowired
    CashierDeskRepository cashierDeskRepository;

    @Autowired
    SocketService socketService;

    @Resource
    MenjinBindingRepository menjinBindingRepository;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @PostMapping(value = "/api/menJinSocket/faceAdd", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "指定旷世门禁添加单个人脸", notes = "通过顾客id")
    public Result faceAdd(@RequestBody @Valid CustomerForm form ){
        List<Integer> customerIdList = new ArrayList<>();
        customerIdList.add(form.getCustomerId());
        if (menJinSocketService.isCustomerGroup(form.getDeskId(),form.getCustomerId(),form.getShopID())){
            JSONObject sendParam = menJinSocketService.createPersonFace(form.getShopID(),form.getDeskId(),customerIdList,1);
            if (sendParam != null) {
                CashierDesk desk = cashierDeskRepository.findById(form.getDeskId());
                menJinSocketService.sendParam(sendParam,desk.getCcode());
            }
        }else {
            throw new ServiceException("无效人员");
        }
       return ResultGenerator.genSuccessResult("success");
    }

    @PostMapping(value = "/api/menJinSocket/customerFaceAdd", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "所有店铺下旷世门禁添加单个人脸", notes = "通过顾客id")
    public Result customerFaceAdd(@RequestBody @Valid CustomerForm form) {
        List<Integer> customerIdList = new ArrayList<>();
        customerIdList.add(form.getCustomerId());
        List<Integer> deskIdList = menJinSocketService.createAllDeskFace(form.getShopID());
        if (null != deskIdList) {
            for (Integer deskId : deskIdList) {
                if (menJinSocketService.isCustomerGroup(deskId,form.getCustomerId(),form.getShopID())){
                    JSONObject sendParam = menJinSocketService.createPersonFace(form.getShopID(),form.getDeskId(),customerIdList,1);
                    if (sendParam != null) {
                        CashierDesk desk = cashierDeskRepository.findById(form.getDeskId());
                        menJinSocketService.sendParam(sendParam,desk.getCcode());
                    }
                }
            }
        }else {
            throw new ServiceException("该店不存在已绑定澎Pad测温版门禁");
        }
        return ResultGenerator.genSuccessResult("success");
    }

    @PostMapping(value = "/api/menJinSocket/groupFaceAdd", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "指定旷世门禁添加会员组人脸", notes = "通过顾客id")
    public Result groupFaceAdd(@RequestBody @Valid CustomerGroupFaceForm form) {
        List<Integer> customerIdList = menJinSocketService.createGroupFace(form.getShopID(),form.getGroupID());
        if (customerIdList != null) {
            JSONObject sendParam = menJinSocketService.createPersonFace(form.getShopID(), form.getDeskId(), customerIdList,1);
            if (sendParam != null) {
                CashierDesk desk = cashierDeskRepository.findById(form.getDeskId());
                menJinSocketService.sendParam(sendParam,desk.getCcode());
            }
        }else {
            return ResultGenerator.genFailResult("该店此会员等级下不存在会员");
        }
        return ResultGenerator.genSuccessResult("success");
    }

    @PostMapping(value = "/api/menJinSocket/bindingFaceAdd", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "旷世门禁初次绑定添加所有人脸", notes = "通过顾客id")
    public Result bindingFaceAdd(@RequestBody @Valid CustomerGroupFaceForm form) {
        JSONObject bindingParam = new JSONObject();
        bindingParam.put("isBinding",1);
        bindingParam.put("shopId",form.getShopID());
        bindingParam.put("deskId",form.getDeskId());
        redisTemplate.convertAndSend("menjin",Base64.getEncoder().encodeToString(bindingParam.toJSONString().getBytes()));
        return ResultGenerator.genSuccessResult("success");
    }


    @PostMapping(value = "/api/menJinSocket/facedelete", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除旷世门禁人脸", notes = "通过顾客id")
    public Result facedelete(@RequestBody @Valid CustomerForm form) {
        CashierDesk desk = cashierDeskRepository.findById(form.getDeskId());
        JSONObject sendParam = menJinSocketService.sendDeleteFace(form.getShopID(),form.getDeskId(),form.getCustomerIDList());
        menJinSocketService.sendParam(sendParam,desk.getCcode());
        return ResultGenerator.genSuccessResult("success");
    }

    @PostMapping(value = "/api/menJinSocket/groupFaceDelete", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "旷世门禁添加人脸", notes = "通过顾客id")
    public Result groupFaceDelete(@RequestBody @Valid CustomerGroupFaceForm form) {
        JSONObject sendParam = menJinSocketService.deleteGroupFace(form.getShopID(),form.getDeskId(),form.getGroupID());
        if (sendParam != null){
            CashierDesk desk = cashierDeskRepository.findById(form.getDeskId());
            menJinSocketService.sendParam(sendParam,desk.getCcode());
        }
        return ResultGenerator.genSuccessResult("success");
    }



    @PostMapping(value = "/api/menJinSocket/menJinOrder")
    @ApiOperation(value = "接受旷世机器发来的门禁信息", notes = "通过顾客id")
    public Result menJinOrder(HttpServletRequest request,
                              HttpServletResponse response) {

        JSONObject jsonObject = JSONObject.parseObject(request.getParameter("json"));
        String faceBase64 = request.getParameter("picture");
        menJinSocketService.createMenJinOrder(jsonObject,faceBase64);
        return ResultGenerator.genSuccessResult("success");
    }

    @PostMapping(value = "/api/menJinSocket/bindingMenjing")
    @ApiOperation(value = "接受旷世机器发来的门禁信息", notes = "通过顾客id")
    public Result bindingMenjing(@RequestBody JSONObject postParam) {
        String id;
        String serialNo = postParam.getString("SerialNo");
        Condition condition = new Condition(CashierDesk.class);
        condition.or().andEqualTo("ccode", serialNo)
                .andEqualTo("deleted", 0);
        List<CashierDesk> deskList = cashierDeskRepository.findByCondition(condition);
        if (null == deskList || deskList.size() == 0) {
            Condition bindingCondition = new Condition(MenjinBinding.class);
            bindingCondition.or().andEqualTo("ccode",serialNo);
            List<MenjinBinding> menjinBindingList = menjinBindingRepository.findByCondition(bindingCondition);
            if (null == menjinBindingList || menjinBindingList.size() == 0) {
                MenjinBinding menjinBinding = new MenjinBinding();
                menjinBinding.setCcode(serialNo);
                menjinBinding.setCreatetime(new Date());
                menjinBinding.setStatus(0);
                menjinBindingRepository.save(menjinBinding);
                id = "bingDing" + menjinBinding.getId();
            }else {
                id = "bingDing" + menjinBindingList.get(0).getId();
            }
        } else {
            id = deskList.get(0).getId().toString();
        }
        return ResultGenerator.genSuccessResult(id);
    }

    @PostMapping(value = "/api/menJinSocket/onMessage")
    @ApiOperation(value = "接受旷世机器发来的门禁信息", notes = "通过顾客id")
    public Result onMessage(@RequestBody JSONObject postParam) {
        menJinSocketService.getMessageFormDesk(postParam);
        return ResultGenerator.genSuccessResult();
    }


}
